<template>
  <div>
    <BasicModal
      @register="ruleRegisterModal"
      v-bind="$attrs"
      :helpMessage="['提示1', '提示2']"
      @ok="addDashboards"
    >
      <BasicForm @register="ruleRegisterForm">
        <template #dashboardsAppSlot>
          <div>
            <Upload
              v-model:file-list="fileList"
              list-type="picture"
              accept="image/png, image/jpeg"
              :beforeUpload="upLoadChange"
              class="upload-list-inline"
            >
              <div
                style="
                  width: 200px;
                  height: 60px;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  border: 1px #999 dashed;
                  border-radius: 5px;
                  cursor: pointer;
                "
              >
                <Icon icon="material-symbols:upload" />
                上传图片
              </div>
            </Upload>
          </div>
        </template>
      </BasicForm>
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import Icon from '/@/components/Icon/src/Icon.vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import {
    addDashboard,
    getTheDashboardInfo,
    editDashBoard,
  } from '/@/api/thingsborad/dashboards/dashboard';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { ref } from 'vue';
  import { Upload } from 'ant-design-vue';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  const emits = defineEmits(['closeAddRuleFalg']);
  let dashboardInfo = ref<any>();
  let fileList = ref<any>();
  let upLoadFile = ref<any>();
  let isEdit = ref<boolean>(false);
  let addSchemas: FormSchema[] = [
    {
      field: 'dashboardsName',
      component: 'Input',
      label: '标题',
      required: true,
      componentProps: {
        placeholder: '请输入仪表盘名称',
      },
    },
    {
      field: 'isShowDashboards',
      component: 'Checkbox',
      label: '在移动端应用中隐藏仪表板',
    },
    {
      field: 'dashboardsApp',
      component: 'Input',
      slot: 'dashboardsAppSlot',
      label: '仪表板图片',
      colProps: {
        span: 24,
      },
    },
    {
      field: 'describe',
      component: 'InputTextArea',
      label: '说明',
      colProps: {
        span: 24,
      },
      componentProps: {
        placeholder: '请输入说明',
      },
    },
  ];
  const [ruleRegisterForm, { validate, resetFields, setFieldsValue }] = useForm({
    layout: 'vertical',
    schemas: addSchemas,
    actionColOptions: {
      span: 24,
    },
    showActionButtonGroup: false,
    showSubmitButton: true,
    showResetButton: false,
    ...modalFormStyleSetting,
  });
  const [ruleRegisterModal, { closeModal, setModalProps }] = useModalInner(async (data) => {
    setModalProps({ loading: true });
    resetFields();
    if (data !== true) {
      isEdit.value = true;
      dashboardInfo.value = await getTheDashboardInfo(data.id);
      if (dashboardInfo.value.image !== null) {
        fileList.value = [
          {
            uid: '-1',
            name: '',
            status: 'done',
            thumbUrl: dashboardInfo.value.image,
          },
        ];
      }
      upLoadFile.value = dashboardInfo.value.image;
      setFieldsValue({
        dashboardsName: dashboardInfo.value.title,
        describe: dashboardInfo.value.configuration.description,
        isShowDashboards: dashboardInfo.value.mobileHide,
        dashboardsSort: dashboardInfo.value.mobileOrder,
      });
    } else {
      isEdit.value = false;
      // fileList.value = [];
    }
    setModalProps({
      loading: false,
      confirmLoading: false,
      ...modalStyleSetting,
    });
  });
  const upLoadChange = (file: File) => {
    // 文件读取
    const reader = new FileReader();

    reader.readAsDataURL(file);
    //获取上传数据
    reader.addEventListener('load', () => {
      const base64: any = reader.result;

      fileList.value.forEach((item) => {
        item.status = 'done';
      });
      upLoadFile.value = base64;
    });
  };
  async function addDashboards() {
    try {
      let validateData = await validate();
      if (isEdit.value) {
        let data = {
          id: dashboardInfo.value.id,
          createdTime: dashboardInfo.value.createdTime,
          tenantId: dashboardInfo.value.tenantId,
          title: validateData.dashboardsName,
          image: upLoadFile.value === undefined ? null : upLoadFile.value,
          assignedCustomers: dashboardInfo.value.assignedCustomers,
          mobileHide: validateData.isShowDashboards,
          mobileOrder: dashboardInfo.value.mobileOrder,
          configuration: {
            description: validateData.describe,
          },
          externalId: dashboardInfo.value.externalId,
          name: dashboardInfo.value.name,
        };
        await editDashBoard(data);
      } else {
        let data = {
          title: validateData.dashboardsName,
          image: upLoadFile.value === undefined ? null : upLoadFile.value,
          mobileHide: validateData.isShowDashboards,
          mobileOrder: validateData.dashboardsSort,
          configuration: {
            description: validateData.describe,
          },
        };
        await addDashboard(data);
      }

      fileList.value = [];
      resetFields();
      emits('closeAddRuleFalg', true);
      closeModal();
    } catch (error) {}
  }
</script>

<style scoped>
  .upload-list-inline :deep(.ant-upload-list-item) {
    float: left;
    width: 200px;
    margin-right: 8px;
  }

  .upload-list-inline [class*='-upload-list-rtl'] :deep(.ant-upload-list-item) {
    float: right;
  }
</style>
